package com.bw.journal.insert

import androidx.lifecycle.viewModelScope
import com.bawei.library_mvi.model.BaseViewModel
import com.bawei.module_journal.insert.JournaInsertIent
import com.bawei.module_journal.insert.JournalInsertState
import com.bawei.module_journal.insert.model.JournalInsertService
import com.bawei.module_journal.list.JournalIntent
import com.bawei.module_journal.list.JournalState

import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch

class JournalInsertViewModel : BaseViewModel<JournaInsertIent>() {
    private val service: JournalInsertService by lazy{ JournalInsertService() }
    private val _states = MutableStateFlow<JournalInsertState>(JournalInsertState.Init)//MutableStateFlow可变
    val states: StateFlow<JournalInsertState>
        get() = _states



    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect{
                when(it){
                    is JournaInsertIent.LoadJournalIntent ->  insert(it)//上传日报
                }
            }
        }
    }

    private fun insert(it: JournaInsertIent.LoadJournalIntent) {
        viewModelScope.launch {
            flow {
                val insertJournal = service.insertJournal(it.requestEntity)
                emit(insertJournal)
            }.collect{
                if(it.statusCode == 200){
                    _states.value = JournalInsertState.InsertJournalSuccessState //上传成功
                }else{
                    _states.value = JournalInsertState.InsertJournalErrorState //上传是被
                }

            }
        }
    }

}